package cn.jolyoulu.cmnservice.serivce.impl;


import cn.jolyoulu.common.redis.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.jolyoulu.cmnservice.constant.ServiceRedisConstant;
import cn.jolyoulu.cmnservice.dao.SysRoleMapper;
import cn.jolyoulu.cmnservice.entity.po.SysRole;
import cn.jolyoulu.cmnservice.serivce.SysRoleService;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private RedisUtils redisUtil;

    @Override
    public SysRole getByRoleType(String roleType) {
        LambdaQueryWrapper<SysRole> ew = new LambdaQueryWrapper<>();
        ew.eq(SysRole::getRoleType,roleType);
        return sysRoleMapper.selectOne(ew);
    }

    @Override
    @Transactional
    public boolean allotMenu(String roleId, List<String> menuIds) {
        sysRoleMapper.deleteRoleMenuByRoleId(roleId);
        if (Objects.nonNull(menuIds) && !menuIds.isEmpty()){
            sysRoleMapper.insertBatchRoleMenu(roleId,menuIds);
        }
        String key = ServiceRedisConstant.getRolePermission(roleId);
        if (redisUtil.exists(key)){
            redisUtil.del(key);
        }
        return true;
    }

    @Override
    public List<SysRole> selectByUserId(String userId) {
        String key = ServiceRedisConstant.getUserRole(userId);
        if (redisUtil.exists(key)){
            return (List<SysRole>) redisUtil.get(key);
        }else {
            QueryWrapper<Object> ew = new QueryWrapper<>();
            ew.eq("sur.user_id",userId);
            ew.eq("sr.del_flag",0);
            List<SysRole> res = sysRoleMapper.selectByUserId(ew);
            if (Objects.nonNull(res)){
                redisUtil.set(key,res,1, TimeUnit.DAYS);
            }
            return res;
        }
    }
}